package com.xc.stock.utils;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;

/**
 * @description: springutils
 * @author: YUAN YONG
 * @create: 2019-07-11
 **/
@Component("MySpringUtils")
public class SpringUtils
		implements ApplicationContextAware, PriorityOrdered, ApplicationListener<ContextRefreshedEvent> {

	public static ApplicationContext ctx;

	public static <T> T getBean(ApplicationContext ctx, Class<T> clazz) {
		Map<String, T> beans = ctx.getBeansOfType(clazz);
		if (beans != null) {
			for (String keys : beans.keySet()) {
				return beans.get(keys);
			}
		}
		return null;
	}

	public static <T> T getBean(Class<T> clazz) {
		return getBean(getApplicationContext(), clazz);
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String n) {
		return (T) getApplicationContext().getBean(n);
	}

	public static ApplicationContext getApplicationContext() {
		return ctx;
	}

    public static List<Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) {
        Map<String, Object> beansWithAnnotation = getApplicationContext().getBeansWithAnnotation(annotationType);
        return beansWithAnnotation.entrySet().stream().map(entry->entry.getValue()).collect(Collectors.toList());
    }
    
	public static void publishEvent(ApplicationEvent event) {
		getApplicationContext().publishEvent(event);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringUtils.ctx = applicationContext;
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE;
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (event.getApplicationContext().getParent() == null) {
		}
	}
}
